package com.jzy.bxb.app.scripts.http.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.jzy.bxb.app.manager.WeatherManager;
import com.jzy.bxb.core.handler.HandlerEntity;
import com.jzy.bxb.core.handler.HttpCode;
import com.jzy.bxb.core.handler.HttpHandler;
import com.jzy.bxb.core.util.HttpUtils;
import com.jzy.bxb.core.util.StringUtil;
import com.jzy.bxb.model.constant.AppConstant;

/**
 * 查询天气
 * <p>
 * http://127.0.0.1:8680/config/weather?city=成都
 * </p>
 * 
 * @author JiangZhiYong QQ:359135103
 */
@HandlerEntity(path="/config/weather")
public class QueryWeatherHandler extends HttpHandler {
	private static final Logger LOGGER=LoggerFactory.getLogger(QueryWeatherHandler.class);

	@Override
	public void run() {
		String city = getString("city");
		if(StringUtil.isEmpty(city)){
			sendError("请求参数错误");
			return;
		}
		
		String info = WeatherManager.getInstance().getWeatherMap().get(city);
		if(info==null){
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Authorization", "APPCODE " + AppConstant.ALI_WEATHER_APPCODE);
			Map<String, String> querys = new HashMap<String, String>();
			querys.put("city", city);
			try {
				HttpResponse response = HttpUtils.doGet(AppConstant.ALI_WEATHER_HOST, AppConstant.ALI_WEATHER_PATH, "get", headers, querys);
				info=EntityUtils.toString(response.getEntity());
			} catch (Exception e) {
				LOGGER.error("天气",e);
			}
			LOGGER.info("天气:{}",info);
			if(!StringUtil.isEmpty(info)){
				WeatherManager.getInstance().getWeatherMap().put(city, info);
			}
		}
		Map<String, Object> map=new HashMap<>(2);
		map.put("code", HttpCode.SUCCESS);
		map.put("info", info);
		getParameter().appendBody(JSON.toJSONString(map));
		response();
	}

}
